const jwt = require("jsonwebtoken");
const { secretKey, tokenKey } = require("../config/auth.json");
const UserModel = require("../models/user");
const RoleModel = require("../models/role");

// 创建JWT登录拦截中间件
const jwtAuth = async (req, res, next) => {
  if (!req.url.includes("/admin")) {
    next();
    return;
  }

  if (req.url.includes("/user/")) {
    next();
    return;
  }
  try {
    const cookies = req.cookies;
    const userToken = jwt.verify(cookies[tokenKey], secretKey);
    req.userToken = userToken;

    // 权限判断
    const objectId = req?.userToken?.oId;
    if (!objectId) {
      throw new Error("UnauthorizedError");
    }

    const userDoc = await UserModel.findOne({ _id: objectId }).populate("roles");
    if (!userDoc) {
      throw new Error("登录用户不存在");
    }

    const user = userDoc.toObject();
    if (user.userName === 'admin') {
      next();
      return
    }
    const rolesId = (user.roles || []).map(role => role._id);

    const roleDocs = await RoleModel.find({_id: {$in: rolesId}}).populate("resource");
    const roles = roleDocs.map(role => role.toJSON());
    const some = roles.some((item) => {
      const resource = item.resource || [];
      return resource.find((res) => res.path.includes(req.url));
    });

    if (!some) {
      throw new Error("RestrictedAccess");
    }

    next();
  } catch (e) {
    if (e.name === "JsonWebTokenError") {
      next(new Error("UnauthorizedError"));
    } else {
      next(e);
    }
  }
};

module.exports.jwtAuth = jwtAuth;
